package com.justalk.dynamic.InvocationHandle;


import android.util.Log;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;


public class OnclickListenerInvocationHandler implements InvocationHandler {

    private static final String TAG = OnclickListenerInvocationHandler.class.getSimpleName();


    private Object target;
    private HashMap<String, Method> methodMethod = new HashMap();

    public OnclickListenerInvocationHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Log.e(TAG, "invoke: method name:" + method);
        if (target != null) {
            //获取需要拦截的方法,实现我们的点击事件来替换系统的点击事件
            String methodName = method.getName();
            Method hookMethod = methodMethod.get(methodName);
            if (hookMethod != null) {
                return hookMethod.invoke(target, args);
            }
        }
        return null;
    }

    /**
     * 从注解中拿到真正的method，同时对应了我们自己定义的方法名。通过reallyMethodName来拿到hookMethod，从而执行
     * hookMethod
     * @param reallyMethodName 真的方法名称
     * @param hookMethod       回调的方法的名称
     */
    public void addMethod(String reallyMethodName, Method hookMethod) {
        methodMethod.put(reallyMethodName, hookMethod);
    }

}
